package org.example.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author xuan
 * @create 2023/9/12
 * HttpObject表示客户端和服务器端相互通信的数据被封装成 HttpObject类型
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    //此方法是用来读取客户端数据的
    @Override
    protected void channelRead0(ChannelHandlerContext context, HttpObject msg) throws Exception {
        //判断 msg 是不是一个 httpRequest请求
        if(msg instanceof HttpRequest) {
            //获取到
            HttpRequest httpRequest = (HttpRequest) msg;
            //获取url
            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求了favicon.ico，不做响应");
                return;
            }

            System.out.println("msg 类型：" + msg.getClass());
            System.out.println("客户端地址" + context.channel().remoteAddress());

            //回复信息给浏览器[http协议]
            ByteBuf content = Unpooled.copiedBuffer("hello，我是服务器", CharsetUtil.UTF_8);

            //构造一个http的响应，即HttpResponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            //将构建好的 response返回
            context.writeAndFlush(response);
        }
    }
}
